import TIM from "tim-wx-sdk-ws";
import TIMUploadPlugin from "tim-upload-plugin";
import timConfig from "../config/tim"; 
import genTestUserSig from '../lib/tim/generate-test-usersig.min.js';
import User from './user'
class Tim {
  /**
   *  @type {Tim}
   * */ 
  static instance = null;
  _SDKInstance = null
  _nextRegMessageID = ''
  _messageList = []
  isCompleted = false

  constructor(){
 
    // 单例模式 
      // 创建 SDK 实例，`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
      let tim = TIM.create(timConfig.options); // SDK 实例通常用 tim 表示
      // 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
      tim.setLogLevel(timConfig.logLevel); // 普通级别，日志量较多，接入时建议使用 
      // 注册 COS SDK 插件
      tim.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin }); 
      this._SDKInstance = tim
    } 

    static getInstance(){
      if(!Tim.instance){
        Tim.instance = new Tim()
      }

      return Tim.instance;
    }

    getSDK(){
      return this._SDKInstance;
    }

    login(){
      const userInfo = User.getUserInfoByLocal()
      console.log(userInfo.id);
      userInfo.id = '1'
      const textUserSig = genTestUserSig(userInfo.id)
      this._SDKInstance.login({
        userID:userInfo.id.toString(),
        userSig: textUserSig.userSig
      })
    }

    logout(){
      this._SDKInstance.logout()
    }

    // 获取信息列表
    async getMessageList(targetUserId,count,number=10){ 
        if(this.isCompleted){
          return this._messageList
        } 
        const res = await this._SDKInstance.getMessageList({
          conversationID:`C2C${targetUserId}`,
          nextReqMessageId: this._nextRegMessageID,
          count:count > 15 ? 15 : count
        })
        // console.log(res);
        this.nextReqMessageId = res.data.nextReqMessageId
        this.isCompleted = res.data.isCompleted
        this._messageList = res.data.messageList 
        return this._messageList
    }

    // 设置消息已读
    async setMessageRead(targetUserId){
      const res = await this._SDKInstance.setMessageRead({
          conversationID:`C2C${targetUserId}`
      })
      return res.data
    }

    // 重置操作
    reset(){
      this._nextRegMessageID = ''
      this.isCompleted = false 
      this._messageList = [] 
      return this
    }
}

export default Tim